import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store/index.js'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style

import { findByToken } from '@/api/login.js'

import { allRole } from './rolesFront.js'
// import { Message } from 'element-ui'
// import axios from 'axios'
import Layout from '@/layout/index'
// import Process from '@/layout/index'

// 解决ElementUI导航栏中的vue-router在3.0版本以上重复点菜单报错问题
const originalPush = Router.prototype.push
Router.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

NProgress.configure({
  showSpinner: false
})

// 在这里对导入模块进行界定,降低耦合
// var i = [0, 1, 2]
// const role0 = JSON.stringify(role0Router)
// const role1 = JSON.stringify(role1Router)
// const role2 = JSON.stringify(role2Router)
// const allRole = {role0, role1, role2}

Vue.use(Router)

const router = new Router({
  routes: [{
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/index'),
    hidden: true
  },
  {
    path: '/404',
    component: () => import('@/views/404'),
    hidden: true
  },
  {
    path: '/',
    component: Layout,
    redirect: '/login',
    children: [
      {
        path: '/login',
        component: () => import('@/views/login/index'),
        meta: {
          name: '首页'
        }
      },
      {
        path: '/404',
        component: () => import('@/views/404'),
        hidden: true,
        meta: {
          name: '404'
        }
      }
    ],
    hidden: true
  },
  {
    path: '/mainF',
    name: 'mainF',
    redirect: '/main',
    component: Layout,
    meta: {
      name: 'Dashboard',
      icon: 'iconfont icon-gongyezujian-yibiaopan'
    },
    children: [{
      path: '/main',
      name: 'main',
      component: () => import('@/views/main/index'),
      meta: {
        name: '首页'
      }
    }]
  },
  {
    path: '/dataCenter',
    name: 'dataCenter',
    redirect: '/process',
    component: Layout,
    meta: {
      name: '数据中心',
      icon: 'iconfont icon-shujukanban'
    },
    children: [{
      path: '/process',
      name: 'process',
      redirect: '/forming',
      component: () => import('@/views/dataCenter/process/index.vue'),
      meta: {
        name: '工艺流程'
      },
      children: [
        {
          path: '/forming',
          name: 'forming',
          component: () => import('@/views/dataCenter/process/forming'),
          meta: {
            name: '压型阶段'
          }
        },
        {
          path: '/form',
          name: 'form',
          component: () => import('@/views/dataCenter/process/forming/form'),
          meta: {
            name: '压型表单'
          },
          hidden: true
        },
        {
          path: '/dipping',
          name: 'dipping',
          component: () => import('@/views/dataCenter/process/dipping'),
          meta: {
            name: '浸渍阶段'
          }
        },
        {
          path: '/tunnelKiln',
          name: 'tunnelKiln',
          component: () => import('@/views/dataCenter/process/tunnelKiln'),
          meta: {
            name: '隧道窑阶段'
          }
        },
        {
          path: '/graphiting',
          name: 'graphiting',
          component: () => import('@/views/dataCenter/process/graphiting'),
          meta: {
            name: '石墨化阶段'
          }
        }
      ]
    },
    {
      path: '/cargo',
      name: 'cargo',
      component: () => import('@/views/dataCenter/cargo'),
      meta: {
        name: '货物管理'
      }
    },
    {
      path: '/warehouse',
      name: 'warehouse',
      component: () => import('@/views/dataCenter/warehouse'),
      meta: {
        name: '仓库管理'
      }
    },
    {
      path: '/formCheck',
      name: 'formCheck',
      component: () => import('@/views/dataCenter/formCheck'),
      hidden: true,
      meta: {
        name: '表单查看'
      }
    },
    {
      path: '/formCheckDip',
      name: 'formCheckDip',
      component: () => import('@/views/dataCenter/formCheckDip'),
      hidden: true,
      meta: {
        name: '表单查看浸渍'
      }
    },
    {
      path: '/formCheckKiln',
      name: 'formCheckKiln',
      component: () => import('@/views/dataCenter/formCheckKiln'),
      hidden: true,
      meta: {
        name: '表单查看隧道窑'
      }
    }
    ]
  },
  {
    path: '/configCenter',
    name: 'configCenter',
    redirect: '/formTemplate',
    component: Layout,
    meta: {
      name: '配置中心',
      icon: 'iconfont icon-icon_yingyongguanli'
    },
    children: [{
      path: '/formTemplate',
      name: 'formTemplate',
      component: () => import('@/views/configCenter/formTemplate'),
      meta: {
        name: '表单模板'
      }
    },
    {
      path: '/processManage',
      name: 'processManage',
      component: () => import('@/views/configCenter/processManage'),
      meta: {
        name: '流程管理'
      }
    },
    {
      path: '/employeeInfo',
      name: 'employeeInfo',
      component: () => import('@/views/configCenter/employeeInfo'),
      meta: {
        name: '员工信息'
      }
    },
    {
      path: '/platform',
      name: 'platform',
      component: () => import('@/views/configCenter/platform'),
      meta: {
        name: '平台参数'
      }
    },
    {
      path: '/parameter',
      name: 'parameter',
      component: () => import('@/views/configCenter/platform/component/parameter'),
      hidden: true
    },
    {
      path: '/analysis',
      name: 'analysis',
      component: () => import('@/views/configCenter/platform/component/analysis'),
      hidden: true
    }
    ]
  },
  {
    path: '/powerManage',
    name: 'powerManage',
    redirect: '/api',
    component: Layout,
    meta: {
      name: '权限管理',
      icon: 'iconfont icon-jichuguanli'
    },
    children: [{
      path: '/api',
      name: 'api',
      component: () => import('@/views/authority/api/index'),
      meta: {
        name: 'api管理'
      }
    },
    {
      path: '/auth',
      name: 'auth',
      component: () => import('@/views/authority/auth/index'),
      meta: {
        name: '权限管理'
      }
    },
    {
      path: '/role',
      name: 'role',
      component: () => import('@/views/authority/role/index'),
      meta: {
        name: '角色管理'
      }
    },
    {
      path: '/user',
      name: 'user',
      component: () => import('@/views/authority/user/index'),
      meta: {
        name: '用户管理'
      }
    }
    ]
  },
  {
    path: '/personF',
    name: 'personF',
    redirect: '/person',
    component: Layout,
    meta: {
      name: '个人中心',
      icon: 'iconfont icon-icon_zhanghao'
    },
    children: [{
      path: '/person',
      name: 'person',
      component: () => import('@/views/person/index')
      // hidden: true
    },
    {
      path: '/modifyPwd',
      name: 'modifyPwd',
      component: () => import('@/views/person/modifyPwd/'),
      meta: {
        name: '修改密码'
      },
      hidden: true
    }
    ]
  }
  ]
})

router.beforeEach((to, from, next) => {
  NProgress.start()
  store.commit('insertCurrentPage', (to.fullPath).substr(1))
  // console.log(to.path)
  // 如果去登录 直接放行
  if (to.path === '/login') {
    next()
    NProgress.done()
  } else {
    // 如果跳过了登录去其它页面 先判断是否具有token
    // console.log(sessionStorage.getItem('Token'))
    if (sessionStorage.getItem('Token')) {
      // 有token的话调用接口获取用户信息 存到vuex里 这样就不会在控制台的本地缓存中找到用户信息
      findByToken(sessionStorage.getItem('Token'))
        .then(res => {
          // console.log('findByToken', res)
          // 请求拦截器将res处理了
          if (res === undefined) {
            next('/login')
            NProgress.done()
            sessionStorage.clear()
            window.location.reload() // 刷新vuex
          }
          // sessionStorage.setItem('loginState', JSON.stringify(res.data.data))
          const payload = res.data.data
          // 将用户信息存到vuex中
          store.commit('insertLoginState', payload)
          // console.log('state', store)

          // 从vuex里面获取数据代替router,假如没有数据则重新获取
          // 对用户状态进行检测,假如跳转到非当前用户权限范围则返回
          try {
            // console.log(to.fullPath)
            // 这里有个问题，假如获取到的role为null,直接会报typeError,不会进入roleState === null,故要try{}catch{}
            const roleState = store.getters.getRole
            // eslint-disable-next-line no-useless-escape
            const toPath = '' + (to.path).substr(1) + ''
            // const toPath = '\"routerName\":\"' + (to.path).substr(1) + '\"'
            // const toPath = (to.path).substr(1)
            // console.log(toPath)
            var roleName = 'role' + roleState
            // console.log(allRole[roleName])
            // console.log(router.options.routes)
            var roleGet = allRole[roleName].toString()
            if (roleGet.indexOf(toPath) === -1) {
              // console.log(toPath)
              // console.log('非法跳转')
              // return new Error('非法跳转')
              // Message.error('非法跳转')
              // localStorage.clear()
              // next('/login')
              next('/404')
              NProgress.done()
            } else {
              next()
              NProgress.done()
            }
          } catch (error) {
            console.log('路由守卫err', error)
            next('/login')
            NProgress.done()
          }
        }).catch(err => {
          console.log('findByToken', err)
        })
    } else {
      // 如果跳过登录去其它页面 没有token 则返回到登录页面
      next('/login')
      NProgress.done()
    }
  }
})

export default router
